package cn.nawang.ebeim.server.thread;

import cn.nawang.ebeim.server.constants.Config;
import cn.nawang.ebeim.server.constants.Constant;
import cn.nawang.ebeim.server.queue.Queues;
import cn.nawang.ebeim.server.task.UploadFileTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * 循环去扫描指定目录下的文件，如果存在就将其移动到临时目录，并加入上传队列
 * Created by GanJc on 2015-11-11 10:36
 */
public class FolderScanner implements Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(FolderScanner.class);

    private static final String UPLOAD_PATH = Config.WORKING_DIR + Constant.FILE_UPLOAD  ;

    private static final String TEMP_UPLOAD_PATH = UPLOAD_PATH +File.separator + Constant.TEMP_DS_FOLDER ;

    public void run() {
        //临时文件夹可能存在未上传的文件。开始前先扫描下临时文件夹
        try {
            scanTempDir();
        } catch (Throwable e) {
            LOG.error("扫描临时文件夹线程异常:" , e);
        }
        //循环扫描上传文件夹,扫描到则移动到临时文件夹
        while (true) {
            try {
                LOG.debug("Scanning path：{}", UPLOAD_PATH);
                File file = new File(UPLOAD_PATH);
                if (file.isDirectory()) {
                    File[] dsList = file.listFiles();
                    for (int i = 0; i < dsList.length; i++) {
                        if (Constant.TEMP_DS_FOLDER.equals(dsList[i].getName())) {
                            continue;
                        }else {
                            scanDsFolder(dsList[i]);
                        }
                    }
                }
                Thread.sleep(Config.SCAN_INTERVAL);
            } catch (Throwable ex) {
                LOG.error("扫描文件夹线程异常:" , ex);
            }
        }
    }

    private void scanTempDir() {
        LOG.debug("Scanning path：{}", TEMP_UPLOAD_PATH);
        File tempDir = new File(TEMP_UPLOAD_PATH);
        if (tempDir.exists() && tempDir.isDirectory()) {
            for (File file : tempDir.listFiles()) {
                if (file.isDirectory()) {
                    for (File f : file.listFiles()) {
                        if (f.isFile()) {
                            putIntoTaskQueue(new UploadFileTask(f.getAbsolutePath()));
                        }
                    }
                }
            }
        }else {
            tempDir.mkdirs();
        }
    }

    private void scanDsFolder(File dsFolder) {
        if (!dsFolder.isDirectory()) {
            return;
        }
        for (File file : dsFolder.listFiles()) {
            String fileName = file.getName();
            if (fileName.startsWith(Constant.TEMP_FILE_PREFIX) ) {
                //临时文件跳过
                continue;
            }else {
                //其他的为新上传文件,1移动到临时目录,2改名,3加入传输队列,等待上传至服务器
                String tempUploadFilePath = TEMP_UPLOAD_PATH + File.separator + dsFolder.getName() + File.separator + fileName;
                File tempUploadFile = new File(tempUploadFilePath);
                if(!tempUploadFile.getParentFile().exists()){
                    tempUploadFile.getParentFile().mkdirs();
                }
                boolean renameTo = file.renameTo(tempUploadFile);
                if(renameTo){
                    putIntoTaskQueue(new UploadFileTask(tempUploadFile.getAbsolutePath()));
                }else {
                    boolean delete = file.delete();
                    LOG.info("{} rename failed, delete:{}" ,file,delete);
                }
            }
        }
    }

    private void putIntoTaskQueue(UploadFileTask uploadFileTask) {
        try {
            if (Queues.uploadFileQueue.contains(uploadFileTask)) {
                LOG.info("文件已存在队列:{}", uploadFileTask);
            } else {
                Queues.uploadFileQueue.put(uploadFileTask);
                LOG.info("put new file into uploadFileQueue:{}", uploadFileTask);
            }
        } catch (InterruptedException e) {
            LOG.error("将文件放入上传队列失败:{}" + uploadFileTask, e);
        }
    }

}
